SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO


/** Create Stored Procedures **/

CREATE PROCEDURE dbo.[DnnProduct_AutomaticStuckOrderHandling_LastOrderStatusesList]
	@WhereClause nvarchar(1000),
	@SortExpression varchar(50),
	@MaximumRows int = null, 
	@StartRowIndex int = null
AS
BEGIN
	SET NOCOUNT ON;

	DECLARE @SQLString NVARCHAR(1000)
	DECLARE @ParmDefinition NVARCHAR(100)

	/* Build the SQL string once.*/
	SET @SQLString = N'WITH ItemRN AS (SELECT ROW_NUMBER() OVER(ORDER BY '+ @SortExpression + N') AS RowNum, LastOrderStatusesId, Name, LastOrderDateTime, LastOrderStatusCode, Action, Timestamp FROM [DnnProduct_AutomaticStuckOrderHandling_LastOrderStatuses] WHERE (1 = 1)'

	IF (LEN(@WhereClause) > 0)
	BEGIN
		SET @SQLString = @SQLString + @WhereClause
	END

	SET @SQLString = @SQLString + N' ) SELECT LastOrderStatusesId, Name, LastOrderDateTime, LastOrderStatusCode, Action, Timestamp FROM ItemRN WHERE RowNum BETWEEN @startRowIndex+1 AND (@startRowIndex+@maximumRows);'
	SET @ParmDefinition = N'@MaximumRows int, @StartRowIndex int'
	EXECUTE sp_executesql @SQLString, @ParmDefinition, @MaximumRows, @StartRowIndex
	
END
GO
